const axios = require('axios');
const cheerio = require('cheerio');
const { URL } = require('url');
const Site = require('../models/Site');
const ErrorResponse = require('../utils/errorResponse');

// @desc    添加网站
// @route   POST /api/sites
// @access  Private
const addSite = async (req, res) => {
  try {
    const { url, name } = req.body;
    const userId = req.user.id;

    // 验证URL格式
    try {
      new URL(url);
    } catch (err) {
      return res.status(400).json({ 
        status: 'error', 
        message: '无效的URL格式' 
      });
    }

    // 检查网站是否已存在
    const siteExists = await Site.findOne({ url, user: userId });
    if (siteExists) {
      return res.status(400).json({ 
        status: 'error', 
        message: '该网站已存在' 
      });
    }

    // 创建网站记录
    const site = await Site.create({
      user: userId,
      url,
      name: name || url
    });

    res.status(201).json({
      status: 'success',
      data: site
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    获取用户所有网站
// @route   GET /api/sites
// @access  Private
const getSite = async (req, res) => {
  try {
    const sites = await Site.find({ user: req.user.id });
    
    res.status(200).json({
      status: 'success',
      data: sites
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    更新网站信息
// @route   PUT /api/sites/:id
// @access  Private
const updateSite = async (req, res) => {
  try {
    const { id } = req.params;
    const { name } = req.body;

    let site = await Site.findById(id);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== req.user.id) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权更新此网站' 
      });
    }

    // 更新网站信息
    if (name) site.name = name;
    await site.save();

    res.status(200).json({
      status: 'success',
      data: site
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    删除网站
// @route   DELETE /api/sites/:id
// @access  Private
const deleteSite = async (req, res) => {
  try {
    const { id } = req.params;

    const site = await Site.findById(id);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== req.user.id) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权删除此网站' 
      });
    }

    await site.remove();

    res.status(200).json({
      status: 'success',
      data: null
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    获取网站统计数据
// @route   GET /api/sites/:id/stats
// @access  Private
const getSiteStats = async (req, res) => {
  try {
    const { id } = req.params;

    const site = await Site.findById(id);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== req.user.id) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权访问此网站' 
      });
    }

    res.status(200).json({
      status: 'success',
      data: site.stats
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    运行网站SEO审核
// @route   POST /api/sites/:id/audit
// @access  Private
const runSiteAudit = async (req, res) => {
  try {
    const { id } = req.params;

    const site = await Site.findById(id);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== req.user.id) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权审核此网站' 
      });
    }

    // 执行SEO审核
    const auditResult = await performSiteAudit(site.url);

    // 保存审核结果
    site.lastAudit = auditResult;
    await site.save();

    res.status(200).json({
      status: 'success',
      data: auditResult
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// 执行网站SEO审核的辅助函数
const performSiteAudit = async (url) => {
  try {
    // 获取网站HTML内容
    const response = await axios.get(url);
    const html = response.data;
    const $ = cheerio.load(html);

    // 分析SEO元素
    const title = $('title').text();
    const metaDescription = $('meta[name="description"]').attr('content');
    const h1Tags = [];
    $('h1').each((i, el) => {
      h1Tags.push($(el).text());
    });

    // 检查图片alt属性
    const imagesWithoutAlt = [];
    $('img').each((i, el) => {
      if (!$(el).attr('alt')) {
        imagesWithoutAlt.push($(el).attr('src'));
      }
    });

    // 检查结构化数据
    const structuredData = $('script[type="application/ld+json"]').length;

    // 返回审核结果
    return {
      url,
      basicSeo: {
        hasTitle: !!title,
        titleLength: title ? title.length : 0,
        hasMetaDescription: !!metaDescription,
        metaDescriptionLength: metaDescription ? metaDescription.length : 0,
        h1Count: h1Tags.length,
        multipleH1: h1Tags.length > 1
      },
      images: {
        totalImages: $('img').length,
        imagesWithoutAlt: imagesWithoutAlt.length,
        examplesWithoutAlt: imagesWithoutAlt.slice(0, 3)
      },
      links: {
        internalLinks: $('a[href^="/"], a[href^="' + url + '"]').length,
        externalLinks: $('a[href^="http"]').not(`a[href^="${url}"]`).length,
        nofollowLinks: $('a[rel="nofollow"]').length
      },
      performance: {
        pageSize: Buffer.byteLength(html, 'utf8') / 1024, // KB
        scriptTags: $('script').length,
        cssFiles: $('link[rel="stylesheet"]').length
      },
      structuredData: {
        hasData: structuredData > 0,
        count: structuredData
      },
      timestamp: new Date()
    };
  } catch (error) {
    throw new Error(`网站审核失败: ${error.message}`);
  }
};

module.exports = {
  addSite,
  getSite,
  updateSite,
  deleteSite,
  getSiteStats,
  runSiteAudit
};node -v
npm -v
npx -v
